'use strict';
import React from 'react';
import {StyleSheet, Text, TouchableOpacity, View} from 'react-native';
import ListView from '../list/ListView';
import CommonListRow from './CommonListRow'
import Button from './../common/Button';
import Images from '../../asset';
import ServicesApi from "../../config/ServicesApi";
import {HorizontalLine} from "../common/CommonLine";
import AuthorRecommendItem from "../item/AuthorRecommendItem";
import BannerComponent from "../swiper/BannerComponent";


class CommonList extends React.PureComponent {

    constructor(props) {
        super(props);
        this.state = {
            dataSource: [],
            showLine: true,
            bannerData: [],
            authorData: [],
        };
        this.page = 1;
    }

    componentDidMount() {
        this.requestDataSources();
        const {dic_code} = this.props;
        if (dic_code === StatusCode.DIC_CODE_LATEST) {
            this.requestBannerList();
            this.requestAuthorList();
        }
    }

    componentDidUpdate(prevProps, prevState) {

    }

    //请求推荐作者列表
    requestAuthorList = async () => {
        const data = {
            search_key: 'rand',
            type: 'recommend',
            focus_user: global.secretKey,
            page: 1,
            limit: 4,
        };
        const result = await Services.post(ServicesApi.RECOMMEND_AUTHOR, data);
        // console.log('推荐作者返回------------->', result);
        if (result.code === StatusCode.SUCCESS_CODE) {
            this.setState({authorData: result.data})
        }
    };

    //请求轮播图列表
    requestBannerList = async () => {
        const result = await Services.post(ServicesApi.HOME_QUERY, {});
        // console.log('轮播图返回------------->', result);
        if (result.code === StatusCode.SUCCESS_CODE) {
            this.setState({bannerData: result.data})
        }
    };

    requestDataSources = async (others = {}) => {
        const {dic_code} = this.props;
        const {uri, query} = this.props;
        const limit = 10;
        let data = {
            limit,
            page: this.page,
            ...query,
            ...others
        };
        const result = await Services.post(uri, data);
        // console.log('2---->', 2);
        // console.log(dic_code, result);
        if (result.code === StatusCode.SUCCESS_CODE) {
            if (this.page === 1) {
                this.setState({dataSource: result.data})
            } else if (this.page > 1 && result.data.length !== 0) {
                let oldData = this.state.dataSource.slice();
                oldData = oldData.concat(result.data);
                this.setState({dataSource: oldData})
            }
        }
        this._listViewRef && this._listViewRef.stopRefresh();
        this._listViewRef && this._listViewRef.stopEndReached({allLoad: result.data.length < limit});
    };

    _onPressItem = (item, index) => {
        // console.log('item---->', item);
        const {dic_code} = this.props;
        if (dic_code === StatusCode.DIC_CODE_VIDEO || item.article_type > 1) {
            RouterHelper.navigate('', 'VideoDetail', {information_id: item.information_id});
        } else if (dic_code === StatusCode.DIC_CODE_LATEST) {
            RouterHelper.navigate('', 'NewestArticleDetail', {item});
        } else {
            RouterHelper.navigate(item.information_title, 'ArticleDetails', {information_id: item.information_id});
        }

    };

    _onPressHeader = () => {

    };

    _onRefresh = () => {
        this.page = 1;
        this.props.dic_code === StatusCode.DIC_CODE_LATEST && this.requestBannerList();
        this.requestDataSources();
    };

    _onEndReached = () => {
        this.page++;
        this.requestDataSources();
    };

    _renderHeader = () => {
        const {headerTitle} = this.state;
        return (
            <View style={styles.header}>
                <Text style={styles.send}>发布状态:</Text>
                <Button
                    style={styles.button}
                    icon={Images.icon_ranking_arrow}
                    showLeftIcon={false}
                    showRightIcon={true}
                    iconStyle={styles.iconStyle}
                    title={headerTitle}
                    titleStyle={styles.titleStyle}
                    onPress={this._onPressHeader}
                />
            </View>
        )
    };

    _renderLine = () => {
        return <HorizontalLine/>
    };

    _renderItem = ({item, index}) => {
        const {dic_code} = this.props;
        return (
            <CommonListRow
                item={item}
                {...item}
                dic_code={dic_code}
                onPress={() => this._onPressItem(item, index)}
            />
        )
    };

    _renderItemSeparator = (info) => {
        return <HorizontalLine style={styles.sep}/>
    };

    _keyExtractor = (item, index) => {
        return `item${index}`
    };

    _captureRef = (v) => {
        this._listViewRef = v
    };

    renderTitleView = (props) => {
        const {title, subTitle, onPressSub, style} = props;
        return (
            <View style={[styles.titleView, style]}>
                <View style={styles.titleLeftView}>
                    <View style={styles.titleLine}/>
                    <Text style={styles.title}>{title}</Text>
                </View>
                <TouchableOpacity onPress={onPressSub}>
                    <Text style={styles.subTitle}>{subTitle}</Text>
                </TouchableOpacity>
            </View>
        )
    };

    _onPressToAuthor = () => {
        // console.log('作者推荐，查看更多');
        RouterHelper.navigate('作者推荐', 'MyFollowFans', {type: Constants.RECOMMEND_TYPE});
    };

    _onPressToAuthorItem = (item) => {
        RouterHelper.navigate('', 'UserCenter', {author_id: this.state.dataSource.author_id})
    };

    _onPressWatch = async (item, i) => {
        // console.log('关注--------->',item);
        let url = ServicesApi.FOCUS_SAVE;
        let data = {
            focus_user: global.secretKey,
            focus_by_user: item.user_id
        };
        const result = await Services.post(url, data);
        // console.log('关注返回---------->',result);
        if (result.code === StatusCode.SUCCESS_CODE) {
            ToastManager.show('关注成功!');
            this.requestAuthorList();
        } else {
            ToastManager.show(result.dec || 'error')
        }
    };

    renderAuthorRecommend = () => {
        return (
            <View>
                <this.renderTitleView
                    title={'作者推荐'}
                    subTitle={'查看更多'}
                    onPressSub={() => this._onPressToAuthor()}
                />
                <View style={styles.authorView}>
                    {this.state.authorData.map((item, i) => {
                        return (
                            <AuthorRecommendItem
                                key={i}
                                item={item}
                                onPress={() => this._onPressToAuthorItem(item)}
                                onPressFollowed={() => this._onPressWatch(item, i)}
                            />
                        )
                    })}
                </View>
            </View>
        )
    };

    renderLeastHeader = () => {
        let {bannerData} = this.state;
        return (
            <BannerComponent
                style={styles.bannerViewWrap}
                bannerData={bannerData}
            />
        );
    };

    render() {
        const {showFilter, dic_code} = this.props;
        const {dataSource} = this.state;
        let showLine = dic_code === StatusCode.DIC_CODE_FOLLOW;
        return (
            <ListView
                ref={this._captureRef}
                initialRefresh={false}
                enableLoadMore={dic_code !== StatusCode.DIC_CODE_LATEST}
                enableRefresh={true}
                data={dataSource}
                keyExtractor={this._keyExtractor}
                renderItem={this._renderItem}
                ItemSeparatorComponent={showLine ? this._renderItemSeparator : null}
                onRefresh={this._onRefresh}
                onEndReached={this._onEndReached}
                // ListHeaderComponent={showFilter ? this._renderHeader : showLine ? this._renderLine : null}
                ListHeaderComponent={dic_code === StatusCode.DIC_CODE_LATEST ? this.renderLeastHeader : null}
                ListFooterComponent={dic_code === StatusCode.DIC_CODE_LATEST ? this.renderAuthorRecommend : null}
            />
        );
    }
}

const styles = StyleSheet.create({
    bannerViewWrap: {
        marginTop: 10,
    },
    sep: {
        marginHorizontal: 15,
    },
    button: {
        paddingVertical: 5,
        marginLeft: 10,
        backgroundColor: 'transparent',
    },
    iconStyle: {
        width: 15,
        height: 15,
        marginRight: 10,
        // backgroundColor: 'red',
    },
    titleStyle: {
        fontSize: FontSize(14),
        // color: '#4185ec'
        color: '#666666'
    },
    header: {
        flexDirection: 'row',
        justifyContent: 'flex-end',
        alignItems: 'center'
    },
    line: {
        height: Theme.minPixel,
        backgroundColor: '#f5f5f5',
        marginTop: 4
    },
    send: {
        color: '#999999',
        fontSize: FontSize(14)
    },
    titleView: {
        marginVertical: 10,
        flexDirection: 'row',
        alignItems: 'center',
        paddingHorizontal: 15,
        justifyContent: 'space-between',
    },
    titleLeftView: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    titleLine: {
        width: 8,
        height: 19,
        backgroundColor: "#ffa64f",
    },
    title: {
        fontFamily: "PingFangSC-Medium",
        fontSize: FontSize(16),
        color: "#333",
        marginLeft: 14,
    },
    subTitle: {
        fontSize: FontSize(14),
        color: "#ffa64f",
    },
    authorView: {
        marginHorizontal: 15,
        marginVertical: 12,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
    },

});

export default CommonList